use anyhow::Result;
use chrono::Local;
use log::LevelFilter;

/// 使用指定的日志级别初始化日志系统
pub fn init_logger(log_level_str: &str) -> Result<()> {
    // 根据字符串确定日志级别
    let log_level = match log_level_str.to_lowercase().as_str() {
        "off" => LevelFilter::Off,
        "error" => LevelFilter::Error,
        "warn" => LevelFilter::Warn,
        "info" => LevelFilter::Info,
        "debug" => LevelFilter::Debug,
        "trace" => LevelFilter::Trace,
        _ => LevelFilter::Info, // 默认为Info级别
    };

    let dispatcher = fern::Dispatch::new()
        .format(|out, message, record| {
            out.finish(format_args!(
                "{} [{}] [{}] {}",
                Local::now().format("%Y-%m-%d %H:%M:%S"),
                record.level(),
                record.target(),
                message
            ))
        })
        .level(log_level)
        // 输出到控制台
        .chain(fern::Output::stdout("\n"));

    // 应用配置
    dispatcher.apply()?;

    Ok(())
}
